<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/9
 * Time: 11:30
 */

namespace backend\services;


use common\services\BasicService;
use mdm\admin\components\MenuHelper;

class MenuService extends BasicService
{
    public function setMenu($userId)
    {
        $menus = MenuHelper::getAssignedMenu($userId, null, function($menu){
            $data = (array)json_decode($menu['data'], true);
            return [
                'id'=>$menu['id'],
                'label' => $menu['name'],
                'url' => $menu['route'],
                'options' => $data,
                'items' => $menu['children'],
            ];
        });
        \Yii::$app->params['menu'] = $menus;
        $activeMenuId = [];
        if(is_array(\Yii::$app->params['menu'])){
            foreach (\Yii::$app->params['menu'] as $menu)
            {
                if('/'.\Yii::$app->requestedRoute == $menu['url'])
                {
                    $activeMenuId[] = $menu['id'];
                    break;
                }
                foreach ($menu['items'] as $subMenu)
                {
                    if('/'.\Yii::$app->requestedRoute == $subMenu['url'])
                    {
                        $activeMenuId[] = $subMenu['id'];
                        $activeMenuId[] = $menu['id'];
                        break 2;
                    }
                }
            }
        }

        \Yii::$app->params['activeMenuId'] = $activeMenuId;
    }
}